package multiplayer.lan;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Iterator;

public class BroadcastPacketsDiscovery implements Runnable {
	private static int 		DEFAULT_PORT=	7650;
	private static int 		DEFAULT_DELAY=	5000;//milliseconds
	private static boolean 	DEFAULT_ACTIVE=	true;
	private static String 	BROADCAST_ADDRESS="255.255.255.255";

	private int delay;	//ms delay 
	private int port;
	private boolean enable;
	private String nick="nome";
	private String msgDiscovery="chess-"+nick+"-"+port;
	DatagramSocket ds;
	public int getDelay() {
		return delay;
	}
	public void setNick(String nick){
		this.nick=nick;
		msgDiscovery="chess-"+nick+"-"+port;
	}
	
	public void setDelay(int delayMs) {
		this.delay = delayMs;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
		msgDiscovery="chess-"+nick+"-"+port;
	}
	public boolean isEnable() {
		return enable;
	}
	public void setEnable(boolean enabl) {
		enable = enabl;
	}


	public BroadcastPacketsDiscovery(int port, int delayMs, boolean enable) {
		this.delay=delayMs;
		this.port=port;
		this.enable=enable;
	}
	public BroadcastPacketsDiscovery() {
		this(DEFAULT_PORT);
	}
	public BroadcastPacketsDiscovery(int port) {
		this(port,DEFAULT_DELAY);
	}
	public BroadcastPacketsDiscovery(int port, int delayMs) {
		this(port,delayMs,DEFAULT_ACTIVE);
	}

	@Override
	public void run() {
		try {
			InetAddress addr=InetAddress.getByName(BROADCAST_ADDRESS);
			ds=new DatagramSocket();
			ds.setBroadcast(true);
			byte [] msg={0};
			DatagramPacket  dp= new DatagramPacket(msg, msg.length,addr,DEFAULT_PORT);

			while(enable){
				msg=msgDiscovery.getBytes();
				dp.setData(msg);
				dp.setLength(msg.length);
				ds.send(dp);
				try {Thread.sleep(delay);} catch (InterruptedException e) {e.printStackTrace();}
			}

		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			ds.close();
		}

	}
	public static void main(String[] args) {
		BroadcastPacketsDiscovery bdp= new BroadcastPacketsDiscovery();
		Thread t= new Thread(bdp);
		t.start();
	}
}
